package com.lvmama.dashboard.core.aop;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.lvmama.dashboard.entity.UserUser;
import com.lvmama.dashboard.model.rop.AjaxResponse;
import com.lvmama.dashboard.utils.ServletUtils;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	
	protected Set<String> excludeMethods = Collections.emptySet();
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取回话ID
        String logsessionid = ServletUtils.getLogsessionid(request, response);
        // 获取用户请求路径
        String path = request.getRequestURI();
        path = path.substring(path.indexOf("/")+1);
        path = path.substring(path.indexOf("/")+1);
        
        List<String> loginExclude = getExclude();
        for(String str : loginExclude) {
        	if(path.startsWith(str)) {
        		return super.preHandle(request, response, handler);
        	}
        	if("ajax/router/rest.do".equals(path)) {
        		String ajaxmethod = request.getParameter("ajaxmethod");
        		if(StringUtils.isNotBlank(ajaxmethod) && excludeMethods.contains(ajaxmethod)) {
        			return super.preHandle(request, response, handler);
        		}
        	}
        }
        // 获取登录用户信息
        UserUser userInfo = ServletUtils.getUser(logsessionid);
        if(userInfo == null) {
        	String url = ServletUtils.getBaseUrl(request, response) + "/login.html";
        	if("ajax/router/rest.do".equals(path)) {
        		return responseAjax(response, url);
        	}
        	response.sendRedirect(url);
        	return false;
        }
		return super.preHandle(request, response, handler);
	}

	private boolean responseAjax(HttpServletResponse response, String url) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		response.setStatus(200);
		AjaxResponse<String> responseBody = new AjaxResponse<String>();
		responseBody.setCode("302");
		responseBody.setData(url);
		JSONObject.toJSONString(responseBody);
		PrintWriter writer = response.getWriter();
		writer.print(JSONObject.toJSONString(responseBody));
		writer.flush();
		writer.close();
		return false;
	}
	
	private List<String> getExclude() {
		List<String> result = new ArrayList<String>();
		result.add("css/");
		result.add("js/");
		result.add("images/");
		result.add("login.jsp");
		return result;
	}
	
	public Set<String> getExcludeMethods() {
		return excludeMethods;
	}

	public void setExcludeMethods(String excludeMethods) {
		this.excludeMethods = commaDelimitedStringToSet(excludeMethods);
	}
	
	public static Set<String> commaDelimitedStringToSet(String s) {
        Set<String> set = new HashSet<String>();
        String[] split = s.split(",");
        for (String aSplit : split) {
            String trimmed = aSplit.trim();
            if (trimmed.length() > 0)
                set.add(trimmed);
        }
        return set;
    }
}
